package com.ecloud.common.data.dynamic;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;

/**
 * 动态数据源处理
 *
 * @author LiuGangQiang Create in 2021/04/27
 */
public class DataSourceContext {
    /**
     * 线程级双端队列
     *
     * @author LiuGangQiang Create in 2021/04/27
     */
    private static final ThreadLocal<Deque<String>> HOLDER = new ThreadLocal<Deque<String>>() {
        /**
         * @see java.lang.ThreadLocal#initialValue()
         */
        @Override
        protected Deque<String> initialValue() {
            /* 初始化一个大小可变的双端队列 */
            return new ArrayDeque<>();
        }
    };
    /**
     * 数据源索引集合用于判断数据源是否存在
     *
     * @author LiuGangQiang Create in 2021/04/27
     */
    public static ArrayList<Object> keys = new ArrayList<>();

    /**
     * 隐藏构造器
     *
     * @author LiuGangQiang Create in 2021/07/20
     */
    private DataSourceContext() {
    }

    /**
     * 获取当前数据源
     *
     * @author LiuGangQiang Create in 2021/04/27
     * @return {@link String}
     */
    public static String getDataSource() {
        /* 获取双端队列顶部信息 */
        String current = HOLDER.get().peek();
        return StringUtils.isBlank(current) ? DynamicDataSource.MASTER : current;
    }

    /**
     * 切换数据源
     *
     * @author LiuGangQiang Create in 2021/04/27
     * @param key 数据源索引
     */
    public static synchronized void switchDataSource(String key) {
        /* 将数据源添加到双端队列顶部 */
        HOLDER.get().push(key);
    }

    /**
     * 清除数据源
     *
     * @author LiuGangQiang Create in 2021/04/27
     */
    public static void clearDataSource() {
        /* 每次清理清除最顶端信息,如果清理完毕队列为空移除队列 */
        Deque<String> deque = HOLDER.get();
        deque.poll();
        if (deque.isEmpty()) {
            HOLDER.remove();
        }
    }

    /**
     * 判断是否包含数据源
     *
     * @author LiuGangQiang Create in 2021/04/27
     * @param key 数据源索引
     * @return {@link Boolean}
     */
    public static boolean containDataSourceKey(Object key) {
        return keys.contains(key);
    }

    /**
     * 删除数据源
     *
     * @author LiuGangQiang Create in 2021/04/27
     * @param key 数据源索引
     * @return {@link Boolean}
     */
    public static boolean delDataSourceKey(Object key) {
        return DataSourceContext.keys.remove(key);
    }

    /**
     * 添加数据源
     *
     * @author LiuGangQiang Create in 2021/04/27
     * @param key 数据源索引
     * @return {@link Boolean}
     */
    public static boolean addDataSourceKey(Object key) {
        return DataSourceContext.keys.add(key);
    }

    /**
     * 添加数据源集合
     *
     * @author LiuGangQiang Create in 2021/04/27
     * @param keys 数据源索引集合
     * @return {@link Boolean}
     */
    public static boolean addDataSourceKeys(Collection<?> keys) {
        return DataSourceContext.keys.addAll(keys);
    }
}
